package _18_剑指OfferII;

import _18_剑指OfferII.datastrcute.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _046_剑指OfferII二叉树的右侧视图 {

    // 深度遍历， 按照root, right, left遍历
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        if (root == null) return results;

        dfs(root, 0, results);
        return results;
    }

    private void dfs(TreeNode root, int deep, List<Integer> results) {
        if (root == null) return;

        // 数组元素，标记第几层
        if (results.size() == deep) results.add(root.val);

        dfs(root.right, deep + 1, results);
        dfs(root.left, deep + 1, results);

    }


    // 层序遍历
    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        if (root == null) return results;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int last = 0;
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                last = node.val;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            results.add(last);
        }
        return results;
    }

}
